package com.elastic.eslearn._0_client;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 避免每次都创建对象，使用单例模式来创建 TransportClient
 */
public class EsUtils {
	private volatile static TransportClient client;
	public static TransportClient getSingleClient() throws UnknownHostException {
		if (null == client) {
			synchronized (TransportClient.class) {
				String CLUSTER_NAME = "elasticsearch";  // 访问 http://10.10.139.42:9200/ 获取
				String HOST_IP = "10.10.139.42";
				int TCP_PORT = 9300;  // 注意是9300
				Settings settings = Settings.builder()
						.put("cluster.name", CLUSTER_NAME)
						.build();
				client = new PreBuiltTransportClient(settings)
						.addTransportAddress(new TransportAddress(InetAddress.getByName(HOST_IP), TCP_PORT));
			}
		}
		return client;
	}
}
